<?php
/**
 * 团队数据管理类
 */

class TeamDataManager {
    private $pdo;
    private $user_id;
    private $logger;

    public function __construct($pdo, $user_id) {
        $this->pdo = $pdo;
        $this->user_id = $user_id;
        $this->logger = new TeamLogger();
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo() {
        try {
            $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$this->user_id]);
            $user = $stmt->fetch();
            
            if (!$user) {
                throw new Exception("用户不存在");
            }
            
            return $user;
        } catch (Exception $e) {
            $this->logger->error("获取用户信息失败", [
                'user_id' => $this->user_id,
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }

    /**
     * 获取团队统计信息
     */
    public function getTeamStats() {
        try {
            $stmt = $this->pdo->prepare("
                SELECT 
                    COUNT(*) as team_size,
                    COALESCE(SUM(total_commission), 0) as total_commission_earned,
                    COALESCE(SUM(tc.commission_amount), 0) as total_commission_paid
                FROM users u
                LEFT JOIN team_commissions tc ON tc.inviter_id = u.id
                WHERE u.inviter_id = ?
            ");
            $stmt->execute([$this->user_id]);
            $stats = $stmt->fetch();
            
            return [
                'team_size' => (int)$stats['team_size'],
                'total_commission_earned' => (float)$stats['total_commission_earned'],
                'total_commission_paid' => (float)$stats['total_commission_paid']
            ];
        } catch (Exception $e) {
            $this->logger->error("获取团队统计失败", [
                'user_id' => $this->user_id,
                'error' => $e->getMessage()
            ]);
            return [
                'team_size' => 0,
                'total_commission_earned' => 0.0,
                'total_commission_paid' => 0.0
            ];
        }
    }

    /**
     * 获取团队成员列表
     */
    public function getTeamMembers($limit = 50, $offset = 0) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT 
                    u.id,
                    u.username,
                    u.balance,
                    u.total_commission,
                    u.created_at,
                    COUNT(t.id) as transaction_count,
                    COALESCE(SUM(t.amount), 0) as total_trading_amount,
                    COALESCE(SUM(t.fee), 0) as total_fees_paid,
                    COALESCE(SUM(tc.commission_amount), 0) as commission_earned
                FROM users u
                LEFT JOIN transactions t ON t.user_id = u.id
                LEFT JOIN team_commissions tc ON tc.user_id = u.id AND tc.inviter_id = ?
                WHERE u.inviter_id = ?
                GROUP BY u.id, u.username, u.balance, u.total_commission, u.created_at
                ORDER BY u.created_at DESC
                LIMIT ? OFFSET ?
            ");
            $stmt->execute([$this->user_id, $this->user_id, $limit, $offset]);
            $members = $stmt->fetchAll();
            
            // 格式化数据
            return array_map([$this, 'formatMemberData'], $members);
        } catch (Exception $e) {
            $this->logger->error("获取团队成员失败", [
                'user_id' => $this->user_id,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 获取最近的分成记录
     */
    public function getRecentCommissions($limit = 20) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT 
                    tc.*,
                    u.username as user_name,
                    t.amount as transaction_amount,
                    t.fee as original_fee
                FROM team_commissions tc
                JOIN users u ON u.id = tc.user_id
                JOIN transactions t ON t.id = tc.transaction_id
                WHERE tc.inviter_id = ?
                ORDER BY tc.created_at DESC
                LIMIT ?
            ");
            $stmt->execute([$this->user_id, $limit]);
            $commissions = $stmt->fetchAll();
            
            // 格式化数据
            return array_map([$this, 'formatCommissionData'], $commissions);
        } catch (Exception $e) {
            $this->logger->error("获取分成记录失败", [
                'user_id' => $this->user_id,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 格式化成员数据
     */
    private function formatMemberData($member) {
        return [
            'id' => (int)$member['id'],
            'username' => htmlspecialchars($member['username']),
            'balance' => (float)$member['balance'],
            'total_commission' => (float)$member['total_commission'],
            'created_at' => $member['created_at'],
            'join_date' => date('Y-m-d', strtotime($member['created_at'])),
            'transaction_count' => (int)$member['transaction_count'],
            'total_trading_amount' => (float)$member['total_trading_amount'],
            'total_fees_paid' => (float)$member['total_fees_paid'],
            'commission_earned' => (float)$member['commission_earned']
        ];
    }

    /**
     * 格式化分成数据
     */
    private function formatCommissionData($commission) {
        return [
            'id' => (int)$commission['id'],
            'user_name' => htmlspecialchars($commission['user_name']),
            'commission_amount' => (float)$commission['commission_amount'],
            'commission_rate' => (float)$commission['commission_rate'],
            'transaction_amount' => (float)$commission['transaction_amount'],
            'original_fee' => (float)$commission['original_fee'],
            'created_at' => $commission['created_at'],
            'formatted_date' => date('Y-m-d H:i', strtotime($commission['created_at']))
        ];
    }

    /**
     * 获取邀请链接
     */
    public function getInviteLink($user) {
        $invite_code = $user['invite_code'] ?? '';
        if (empty($invite_code)) {
            return '';
        }
        
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'];
        
        return "{$protocol}://{$host}/register.php?invite=" . urlencode($invite_code);
    }

    /**
     * 验证用户权限
     */
    public function validateUserAccess() {
        if (!$this->user_id) {
            throw new Exception("用户未登录");
        }
        
        $user = $this->getUserInfo();
        if (!$user) {
            throw new Exception("用户不存在");
        }
        
        return true;
    }
}

/**
 * 团队日志记录类
 */
class TeamLogger {
    private $log_file;

    public function __construct() {
        $this->log_file = __DIR__ . '/../logs/team.log';
        $this->ensureLogDirectory();
    }

    private function ensureLogDirectory() {
        $log_dir = dirname($this->log_file);
        if (!is_dir($log_dir)) {
            mkdir($log_dir, 0755, true);
        }
    }

    public function info($message, $context = []) {
        $this->log('INFO', $message, $context);
    }

    public function error($message, $context = []) {
        $this->log('ERROR', $message, $context);
    }

    public function warning($message, $context = []) {
        $this->log('WARNING', $message, $context);
    }

    private function log($level, $message, $context = []) {
        $timestamp = date('Y-m-d H:i:s');
        $context_str = !empty($context) ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $log_entry = "[{$timestamp}] {$level}: {$message}{$context_str}" . PHP_EOL;
        
        file_put_contents($this->log_file, $log_entry, FILE_APPEND | LOCK_EX);
    }
}

/**
 * 团队数据缓存类
 */
class TeamDataCache {
    private $cache_dir;
    private $cache_time = 300; // 5分钟缓存

    public function __construct() {
        $this->cache_dir = __DIR__ . '/../cache/team';
        $this->ensureCacheDirectory();
    }

    private function ensureCacheDirectory() {
        if (!is_dir($this->cache_dir)) {
            mkdir($this->cache_dir, 0755, true);
        }
    }

    public function get($key) {
        $cache_file = $this->cache_dir . '/' . md5($key) . '.cache';
        
        if (!file_exists($cache_file)) {
            return null;
        }
        
        if (time() - filemtime($cache_file) > $this->cache_time) {
            unlink($cache_file);
            return null;
        }
        
        $data = file_get_contents($cache_file);
        return json_decode($data, true);
    }

    public function set($key, $data) {
        $cache_file = $this->cache_dir . '/' . md5($key) . '.cache';
        file_put_contents($cache_file, json_encode($data, JSON_UNESCAPED_UNICODE), LOCK_EX);
    }

    public function delete($key) {
        $cache_file = $this->cache_dir . '/' . md5($key) . '.cache';
        if (file_exists($cache_file)) {
            unlink($cache_file);
        }
    }

    public function clear() {
        $files = glob($this->cache_dir . '/*.cache');
        foreach ($files as $file) {
            unlink($file);
        }
    }
}
?>
